﻿using LD.Common;
using LD.Host;
using LD.PLC;
using System;
using System.Collections.Generic;
using System.IO;

namespace LD
{
    public class TcpIpService
    {
        private string filePath = Path.Combine(Appbus.BasePath, "Config\\Communication.config");
        private static TcpIpService instance;
        private static object locker = new object();
        public static TcpIpService Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                            instance = new TcpIpService();
                    }
                }
                return instance;
            }
        }
        public List<TcpIpParameModel> GetParameList { get; private set; }

        public Dictionary<string, BaseCommunication> CommuniDic;
        public void Load()
        {
            GetParameList = JsonSerializeHelper.Load<List<TcpIpParameModel>>(filePath);
            if (GetParameList == null)
                GetParameList = new List<TcpIpParameModel>();
        }

        public BaseCommunication this[string key]
        {
            get
            {
                if (CommuniDic.ContainsKey(key))
                    return CommuniDic[key];
                return null;
            }
        }
        public void Start()
        {
            foreach (var item in CommuniDic)
            {
                item.Value.Connect();
            }
        }
        public void Init()
        {
            if (CommuniDic == null)
                CommuniDic = new Dictionary<string, BaseCommunication>();

            foreach (var item in GetParameList)
            {
                switch (item.ConnectType)
                {
                    case 1:
                        CommuniDic.Add(item.Name, new ScanerHelper(item));
                        break;
                    case 2:
                        CommuniDic.Add(item.Name, new TcpClientHelper(item));
                        break;
                    case 3:
                        CommuniDic.Add(item.Name, new CCDClientEx(item));
                        break;
                    case 4:
                        if (Cache.GetCache(CONST.MES_IP) != null)
                            item.Ip = Cache.GetCache(CONST.MES_IP).ToString();
                        CommuniDic.Add(item.Name, new BaliService(item));
                        break;
                    case 5:
                        PLCFactory.Instance?.Start(new HDParamModel()
                        {
                            Address = item.Ip,
                            Port = item.Port,
                            TimeOut = 2000
                        });
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
